import React, { PureComponent } from 'react';

import { Input, Tabs, Row, Typography, Col, Button, Icon, Select, Form, Popover } from 'antd';

import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import * as utils from '../utils/treeUtils';
import { showConfirm } from '@/utils/utils';

const { Text } = Typography;

const FormItem = Form.Item;

const { TabPane } = Tabs;
const { Option } = Select;

@connect(state => ({
  versions: state.ContractPlanVersions.data,
  searchItems: state.ContractPlanItems.searchItems,
}))
@Form.create()
export default class PageTop extends PureComponent {
  state = {
    expandForm: false,
    visible: false,
  };

  // 根据查询条件搜索
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form, match } = this.props;
    const query = form.getFieldsValue();
    dispatch({
      type: 'ContractPlanItems/saveQuery',
      payload: { query, category: match.params.category },
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { dispatch, form, match } = this.props;
    const query = form.getFieldsValue();
    form.resetFields();
    dispatch({
      type: 'ContractPlanItems/saveQuery',
      payload: { query, category: match.params.category },
    });
  };

  // 切换搜索条件的展示方式
  toggleForm = () => {
    const self = this;
    this.setState({
      expandForm: !self.state.expandForm,
    });
    this.props.expandForm(!self.state.expandForm);
  };

  // 搜索条件的展示方式———展开
  renderAdvancedForm = () => {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      style: { marginBottom: 0 },
    };
    const { getFieldDecorator } = this.props.form;
    const { searchItems, match } = this.props;
    // 获取显示的下拉框
    const formItems = utils.getSelects(match.params.category);

    // 产品属性
    const decorationStandard = utils.getSearchTypeItems(
      searchItems.org_build,
      'freeTypeName',
      'freeTypeCode',
    );
    const businessType = utils.getSearchTypeItems(
      searchItems.org_build,
      'businessTypeName',
      'businessTypeCode',
    );
    const proType = utils.getSearchTypeItems(searchItems.org_build, 'proTypeName', 'proTypeCode');
    // 下拉框的值
    const options = {
      productConstitute: utils.getSearchTypeItems(
        searchItems.org_product,
        'productName',
        'productCode',
      ), // 产品构成
      supplyBatch: utils.getSearchTypeItems(searchItems.org_batch, 'name', 'code'), // 供应批次
      decorationStandard: utils.getSearchTypeItems(
        searchItems.org_product,
        'freeTypeName',
        'freeTypeCode',
      ), // 装修标准
      // attributeTag, //属性标签
      trade: utils.getSearchTypeItems(searchItems.org_product, 'proProductName', 'proProductCode'), // 业态
      build: utils.getSearchTypeItems(searchItems.org_build, 'name', 'code'), // 楼栋
      tradeAttr: _.concat(decorationStandard, businessType, proType), // 产品属性
      area: utils.getSearchTypeItems(searchItems.org_build, 'areaPart'), // 面积段
    };
    // console.log('options.productConstitute',searchItems.org_product)
    return (
      <Form onSubmit={this.handleSearch} layout="horizontal">
        <Row type="flex" justify="space-around" align="middle">
          <Col md={20} sm={24}>
            <Row type="flex" justify="space-around" align="middle">
              {formItems.map((selects, index) => (
                <Col md={selects.span} sm={24} key={index}>
                  <FormItem {...formItemLayout} label={selects.label}>
                    {getFieldDecorator(selects.id, {
                      initialValue: '',
                    })(
                      <Select size="small" placeholder="请选择">
                        <Option value="">全部</Option>
                        {options[selects.id] && options[selects.id].length > 0
                          ? options[selects.id].map(value => (
                              <Option key={value.code} value={value.code}>
                                {value.name}
                              </Option>
                            ))
                          : ''}
                      </Select>,
                    )}
                  </FormItem>
                </Col>
              ))}
            </Row>
          </Col>
          <Col md={4} sm={24} justify="space-around" align="middle">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  // 选择搜索条件的展示方式
  renderForm = () => (this.state.expandForm ? this.renderAdvancedForm() : null);

  // 版本详情
  editionDetail = currentState => (
    <p>
      {currentState[0].versionAreaSource ? (
        <Text>{`基于面积计划版本：${currentState[0].versionAreaSource}`}，</Text>
      ) : null}
      &nbsp;
      {currentState[0].versionBuildSource ? (
        <Text>{`基于楼栋计划版本：${currentState[0].versionBuildSource}`}</Text>
      ) : null}
    </p>
  );

  render() {
    const { params } = this.props.match;

    const activeKey = params.category;
    const { versions } = this.props;
    const { visible } = this.state;
    let versionState = '';
    let currentState = [];
    if (versions.length > 0 && params.version) {
      currentState = _.filter(versions, { versionId: params.version });
      if (currentState.length) {
        versionState = currentState[0].versionStateCode;
      }
    }
    return (
      <>
        {!params.edit ? (
          <>
            <div className="header-categories">
              <Tabs
                activeKey={activeKey}
                animated={false}
                onChange={key => {
                  router.push(
                    `/OperatingPlan/ContractPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${key}`,
                  );
                }}
                size="large"
              >
                <TabPane tab="月度动态版" key="dynamic"></TabPane>
                <TabPane tab="大定价版" key="pricing"></TabPane>
                <TabPane tab="战规版" key="strategy"></TabPane>
                <TabPane tab="投资版" key="investment"></TabPane>
              </Tabs>
            </div>
            <div className="header-search-btns">
              <Button key="1" onClick={() => this.props.createPriceVersion()} type="primary">
                创建版本
              </Button>
              {/*
                not_prepared 代编制
                organization 编制中
                examined_approved 待提交审批
                approved 审批中
                failure_approved 审批已驳回
                success_approved 审批通过
              */}
              {versions && versions.length ? (
                <>
                  {versionState === 'not_prepared' ||
                  versionState === 'organization' ||
                  versionState === 'failure_approved' ? (
                    <Button
                      onClick={() =>
                        showConfirm(
                          () => this.props.deletePriceVersion(),
                          '确定要删除该版本吗？',
                          '删除后，该版本将不可用。',
                        )
                      }
                      key="3"
                      type="primary"
                    >
                      删除版本
                    </Button>
                  ) : null}
                  {versionState === 'not_prepared' ||
                  versionState === 'organization' ||
                  versionState === 'examined_approved' ||
                  versionState === 'failure_approved' ? (
                    <Button
                      onClick={() => {
                        router.push(`${this.props.match.url}/edit`);
                      }}
                      key="2"
                      type="primary"
                    >
                      编辑价格
                    </Button>
                  ) : null}
                  <Button onClick={this.toggleForm}>
                    高级筛选
                    {this.state.expandForm ? <Icon type="up" /> : <Icon type="down" />}
                  </Button>
                </>
              ) : null}
            </div>
          </>
        ) : null}
        <div className="header-search-area">{this.renderForm()}</div>
        {versions.length && currentState.length ? (
          <>
            {!params.edit ? (
              <Row type="flex" justify="space-between" align="middle">
                <Col span={4}>
                  <Select
                    onChange={value => {
                      router.replace(
                        `/OperatingPlan/ContractPlan/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                      );
                    }}
                    size="small"
                    className="version-select"
                    value={currentState[0].versionId}
                  >
                    {versions.map(val => (
                      <Option key={val.versionId} value={val.versionId}>
                        {val.versionName + val.versionNum}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col span={20}>
                  <Row type="flex" justify="space-between" align="middle">
                    <Col>
                      {params.edit ? (
                        <Text className="version-current">{currentState[0].versionName}</Text>
                      ) : null}
                      <Text className="version-status dot" strong>
                        {currentState[0].versionState}
                      </Text>
                    </Col>
                    <Col>
                      <Popover
                        content={this.editionDetail(currentState)}
                        title="版本信息"
                        trigger="hover"
                        placement="bottomRight"
                      >
                        <Button style={{ color: '#4f84ff', border: 'solid 1px #4f84ff' }}>
                          <Icon type="snippets" />
                          版本信息
                        </Button>
                      </Popover>

                      {/* <Button
                        style={{
                          color: 'rgba(255, 141, 26, 1)',
                          marginLeft: '5px',
                          border: 'solid 1px rgba(255, 141, 26, 1)',
                        }}
                        onClick={this.handleAlterationBlock}
                      >
                        <Icon type="snippets" />
                        版本变动
                      </Button> */}
                    </Col>
                  </Row>
                </Col>
              </Row>
            ) : (
              <>
                <Row
                  className="header-version-area header-version-edit-area"
                  type="flex"
                  justify="space-around"
                  align="middle"
                >
                  <Col className="version-details" md={params.edit ? 22 : 20} sm={24}>
                    <Text className="version-current">{currentState[0].versionName}</Text>
                    <Text className="version-status dot" strong>
                      编辑中
                    </Text>
                    &nbsp; &nbsp;
                    {currentState[0].versionAreaSource ? (
                      <Text>{`基于面积计划版本：${currentState[0].versionAreaSource}`}，</Text>
                    ) : null}
                    &nbsp;
                    {currentState[0].versionBuildSource ? (
                      <Text>{`基于楼栋计划版本：${currentState[0].versionBuildSource}`}</Text>
                    ) : null}
                  </Col>
                  <Col md={2}>
                    <Row type="flex" justify="end">
                      <Col md={24}>
                        <Button
                          onClick={() => {
                            console.log(this.props);
                          }}
                          key="2"
                          className="yellow-button"
                          disabled
                        >
                          导入价格
                        </Button>
                      </Col>
                    </Row>
                  </Col>
                </Row>
              </>
            )}
          </>
        ) : null}
      </>
    );
  }
}
